package models

import (
	"time"
	"weiboxs.com/new_h_glasses/utils"
)

import (
	"github.com/beego/beego/v2/client/orm"
)

type EquipmentData struct {
	Id                  int64     `form:"data_id"`
	Archives            *Archives `orm:"rel(one)"`
	RightVision         string
	LeftVision          string
	RightCorrectVision  string
	LeftCorrectVision   string
	LeftBallDiameter    string //球镜
	RightBallDiameter   string
	LeftColumnDiameter  string //柱镜
	RightColumnDiameter string
	LeftAxial           string //轴向
	RightAxial          string
	Summary             string
	CreatedAt           int64
	UpdatedAt           int64
	IsNew               int
}

type ScreeningDataQueryParam struct {
	BaseQueryParam
	Filter      string
	Mobile      string
	ScreeningId string `json:"screening_id"`

	Name     string `json:"name"`
	SchoolId int64  `json:"school_id"`
	Grade    string `json:"grade"`
	Class    string `json:"class"`
	Planid   string `json:"planid"`
}

func (a *EquipmentData) TableName() string {
	return ScreeningDataTableName()
}

func ScreeningDataTableName() string {
	return TableName("sc_screening_data")
}

//添加筛查信息
func (a *EquipmentData) Insert() (int64, error) {

	a.CreatedAt = time.Now().Unix()
	a.UpdatedAt = time.Now().Unix()

	return orm.NewOrm().Insert(a)
}

//修改信息
func (a *EquipmentData) Update(fields ...string) error {

	a.UpdatedAt = time.Now().Unix()

	field, _ := utils.ReflectModelFields(a, fields...)

	if _, err := orm.NewOrm().Update(a, field...); err != nil {
		return err
	}
	return nil
}

//单条档案查询
func GetScreeningDataById(id int64) (*EquipmentData, error) {
	r := new(EquipmentData)
	r.Id = id
	err := orm.NewOrm().Read(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}

//按档案ID获取数据
func GetScreeningDataByScreeningId(id int64) (*EquipmentData, error) {
	r := &EquipmentData{}
	orm.NewOrm().QueryTable(ScreeningDataTableName()).Filter("screening_id", id).One(r)
	return r, nil
}

//删除档案数据
func ScreeningDataDelete(id int64) error {
	to,_ := orm.NewOrm().Begin()
	if _, err := to.QueryTable(ScreeningDataTableName()).Filter("id", id).Delete(); err != nil { //删除子表数据
		to.Rollback()
		return err
	}
	to.Commit()
	return nil
}

//查询分页数据
func ScreeningDataPageList(params *ScreeningDataQueryParam) ([]*EquipmentData, int64) {
	query := orm.NewOrm().QueryTable(ScreeningDataTableName())
	data := make([]*EquipmentData, 0)

	sortorder := "-Id"
	if len(params.Sort) > 0 {
		sortorder = params.Sort
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}
	cond := orm.NewCondition()

	if len(params.ScreeningId) > 0 {
		cond = cond.And("screening_id", params.ScreeningId)
	}
	if len(params.Mobile) > 0 {
		cond = cond.And("mobile", params.Mobile)
	}
	query = query.SetCond(cond)

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&data)

	return data, total
}
